package cn.rubintry.bug.lib.network.http.interceptor

import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.IOException
import java.net.HttpURLConnection.HTTP_CLIENT_TIMEOUT


/**
 * 网络连接失败重试拦截器
 */
class NetWorkRetryInterceptor : Interceptor {

    private var timeCount = 0


    companion object{
        @JvmStatic
        fun default() : Interceptor{
            return NetWorkRetryInterceptor()
        }
    }

    /**
     * 直接调chain.proceed(request)容易抛出ConnectFailedException，这样就违背初衷了，故而使用try catch进行异常捕获
     */
    override fun intercept(chain: Interceptor.Chain): Response {
        timeCount = 0
        val request = chain.request()
        //连接超时时间
        val connectTimeOut = chain.connectTimeoutMillis()
        return try {
            chain.proceed(request)
        }catch (e: IOException){
            var response = try {
                val response = chain.proceed(request)
                response
            }catch (e: IOException){
                Response.Builder()
                    .protocol(Protocol.HTTP_2)
                    .message("连接超时")
                    .request(request)
                    .code(HTTP_CLIENT_TIMEOUT)
                    .body("".toResponseBody("application/json".toMediaType()))
                    .build()
            }
            while (timeCount < connectTimeOut){
                try {
                    if(response.body != null){
                        response.close()
                    }
                    response = chain.proceed(request)
                    //成功拿到响应才会执行break
                    break
                }catch (e: IOException){
                    //如果是手动取消的，那本次请求就不再重试
                    if(e.message == "Canceled"){
                        break
                    }
                }
                Thread.sleep(3000)
                timeCount += 3000
            }
            response
        }
    }
}